package com.zg.ktcomwan.datasource

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.zg.core.ext.logI
import com.zg.ktcomwan.model.ArticleBean
import com.zg.ktcomwan.repository.ProjectRepositroty

/***
 * @Author:      zxd
 * @CreateDate:  2021/7/7 9:36
 * @Description: DataSource
 * abstract class PagingSource<Key : Any, Value : Any>
 * Key：分页标识类型，如页码，则为Int
 * Value：返回列表元素的类型
 */
class ProjectDataSource(private val repository: ProjectRepositroty, private val cid: Int) :
    PagingSource<Int, ArticleBean>() {
    // Return the position of data when refresh RecyclerView.
    // 刷新 RecyclerView 时返回数据的位置。
    override fun getRefreshKey(state: PagingState<Int, ArticleBean>): Int? {
        return 1
    }

    companion object {
        private const val START_INDEX = 1
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ArticleBean> {
        val page = params.key ?: START_INDEX
        logI("page:${page}")

        return try {
            // Get data from DataSource 从数据源获取数据
            val articleList = repository.getArticleList(page, cid)
            logI("size:${articleList.data.datas.size}")
            // Return data to RecyclerView by LoadResult
            //通过 LoadResult 将数据返回给 RecyclerView
            LoadResult.Page(
                articleList.data.datas,//需要加载的数据
                if (page <= START_INDEX) null else page - 1,//prevKey 如果可以往上加载更多就设置该参数，否则不设置（传 null 表示没有上一页）
                if (articleList.data.datas.isEmpty()) null else page + 1//nextKey 加载下一页的key 如果传null就说明到底了
            )
        } catch (exception: Exception) {
            logI("exeception${exception}")
            // Return exception by LoadResult
            LoadResult.Error(exception)
        }
    }
}